<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />









  <meta name="baidu-site-verification" content="Q7ugSRSO7V" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="依赖注入1. 依赖 如果在 Class A 中，有 Class B 的实例，则称 Class A 对 Class B 有一个依赖。例如下面类 Human 中用到一个 Father 对象，我们就说类 Human 对类 Father 有一个依赖。public class Human &amp;#123;    ...    Father father;    ...    public Human() &amp;#1">
<meta property="og:type" content="article">
<meta property="og:title" content="chimps">
<meta property="og:url" content="http://yoursite.com/php/设计模式/index.html">
<meta property="og:site_name" content="chimps">
<meta property="og:description" content="依赖注入1. 依赖 如果在 Class A 中，有 Class B 的实例，则称 Class A 对 Class B 有一个依赖。例如下面类 Human 中用到一个 Father 对象，我们就说类 Human 对类 Father 有一个依赖。public class Human &amp;#123;    ...    Father father;    ...    public Human() &amp;#1">
<meta property="og:updated_time" content="2017-04-23T14:45:17.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="chimps">
<meta name="twitter:description" content="依赖注入1. 依赖 如果在 Class A 中，有 Class B 的实例，则称 Class A 对 Class B 有一个依赖。例如下面类 Human 中用到一个 Father 对象，我们就说类 Human 对类 Father 有一个依赖。public class Human &amp;#123;    ...    Father father;    ...    public Human() &amp;#1">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":30},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/php/设计模式/"/>





  <title>  | chimps </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?dcb994042608bdb310eff950ba755ff1";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">chimps</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/php/设计模式/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="chimps">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="chimps">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-04-23T22:43:53+08:00">
                2017-04-23
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/php/" itemprop="url" rel="index">
                    <span itemprop="name">php</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a class="cloud-tie-join-count" href="/php/设计模式/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count join-count" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="依赖注入"><a href="#依赖注入" class="headerlink" title="依赖注入"></a>依赖注入</h1><h2 id="1-依赖"><a href="#1-依赖" class="headerlink" title="1. 依赖"></a>1. 依赖</h2><blockquote>
<p>如果在 Class A 中，有 Class B 的实例，则称 Class A 对 Class B 有一个依赖。例如下面类 Human 中用到一个 Father 对象，我们就说类 Human 对类 Father 有一个依赖。<br><figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Human</span> </span>&#123;</div><div class="line">    ...</div><div class="line">    Father father;</div><div class="line">    ...</div><div class="line">    <span class="keyword">public</span> Human() &#123;</div><div class="line">        father = <span class="keyword">new</span> Father();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>仔细看这段代码我们会发现存在一些问题：</p>
<ol>
<li>如果现在要改变 father 生成方式，如需要用new Father(String name)初始化 father，需要修改 Human 代码；</li>
<li>如果想测试不同 Father 对象对 Human 的影响很困难，因为 father 的初始化被写死在了 Human 的构造函数中；</li>
<li>如果new Father()过程非常缓慢，单测时我们希望用已经初始化好的 father 对象 Mock 掉这个过程也很困难。<h2 id="2-依赖注入"><a href="#2-依赖注入" class="headerlink" title="2. 依赖注入"></a>2. 依赖注入</h2>上面将依赖在构造函数中直接初始化是一种 Hard init 方式，弊端在于两个类不够独立，不方便测试。我们还有另外一种 Init 方式，如下：<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Human</span> </span>&#123;</div><div class="line">    ...</div><div class="line">    Father father;</div><div class="line">    ...</div><div class="line">    <span class="keyword">public</span> Human(Father father) &#123;</div><div class="line">        this.father = father;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
</ol>
<p>上面代码中，我们将 father 对象作为构造函数的一个参数传入。在调用 Human 的构造方法之前外部就已经初始化好了 Father 对象。像这种非自己主动初始化依赖，而通过外部来传入依赖的方式，我们就称为依赖注入。<br>现在我们发现上面 1 中存在的两个问题都很好解决了，简单的说依赖注入主要有两个好处：</p>
<ol>
<li>解耦，将依赖之间解耦。</li>
<li>因为已经解耦，所以方便做单元测试，尤其是 Mock 测试。<h1 id="工厂模式"><a href="#工厂模式" class="headerlink" title="工厂模式"></a>工厂模式</h1>其实，学习工厂模式之前，我们需要了解最基本的php类的一个特性，多态，有句话写的不错<code>“多态是指在面向对象中能够根据使用类的上下文来重新定义或改变类的性质和行为”</code>。根据参数，来确定类的性质，其实就是多态的诠释。<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">createObj</span><span class="params">($operate)</span></span>&#123;</div><div class="line">        <span class="keyword">switch</span> ($operate)&#123;</div><div class="line">            <span class="keyword">case</span> <span class="string">'+'</span>:</div><div class="line">                <span class="keyword">return</span> <span class="keyword">new</span> OperationAdd();</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'-'</span>:</div><div class="line">                <span class="keyword">return</span> <span class="keyword">new</span> OperationSub();</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'*'</span>:</div><div class="line">                <span class="keyword">return</span> <span class="keyword">new</span> OperationSub();</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            <span class="keyword">case</span> <span class="string">'/'</span>:</div><div class="line">                <span class="keyword">return</span> <span class="keyword">new</span> OperationDiv();</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line">$test=Factory::createObj(<span class="string">'/'</span>);</div><div class="line">$result=$test-&gt;getValue(<span class="number">23</span>,<span class="number">0</span>);</div><div class="line"><span class="keyword">echo</span> $result;</div></pre></td></tr></table></figure>
</li>
</ol>
</blockquote>
<h1 id="loc容器（依赖注入和控制反转）"><a href="#loc容器（依赖注入和控制反转）" class="headerlink" title="loc容器（依赖注入和控制反转）"></a>loc容器（依赖注入和控制反转）</h1><blockquote>
<p>这儿是学院君分享的loc容器，我个人感觉写的确实不错，但是和上一个结合起来，相信更加通俗易懂.<br>上面的例子中，只是写了<code>$di = new  Di();</code>却没有写出<code>Di</code>是什么样子的，下面的例子恰恰给出了这一点。<br>这只是一个小的模型，真正的 IoC 容器会根据类的依赖需求，自动在注册、绑定的一堆实例中搜寻符合的依赖需求，并自动注入到<code>构造函数参数</code>中去。<br><figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span></span></div><div class="line">&#123;</div><div class="line">    <span class="keyword">protected</span> $binds;</div><div class="line"></div><div class="line">    <span class="keyword">protected</span> $instances;</div><div class="line">    </div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">bind</span><span class="params">($abstract, $concrete)</span></span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">if</span> ($concrete <span class="keyword">instanceof</span> Closure) &#123;</div><div class="line">            <span class="keyword">$this</span>-&gt;binds[$abstract] = $concrete;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="keyword">$this</span>-&gt;instances[$abstract] = $concrete;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    </div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">make</span><span class="params">($abstract, $parameters = [])</span></span></div><div class="line">    &#123;</div><div class="line">        <span class="keyword">if</span> (<span class="keyword">isset</span>(<span class="keyword">$this</span>-&gt;instances[$abstract])) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;instances[$abstract];</div><div class="line">        &#125;</div><div class="line"></div><div class="line">        array_unshift($parameters, <span class="keyword">$this</span>);</div><div class="line"></div><div class="line">        <span class="keyword">return</span> call_user_func_array(<span class="keyword">$this</span>-&gt;binds[$abstract], $parameters);</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// ioc的使用</span></div><div class="line"><span class="comment">// 创建一个容器（后面称作超级工厂）</span></div><div class="line">$container = <span class="keyword">new</span> Container;</div><div class="line"></div><div class="line"><span class="comment">// 向该 超级工厂添加超人的生产脚本</span></div><div class="line">$container-&gt;bind(<span class="string">'superman'</span>, <span class="function"><span class="keyword">function</span><span class="params">($container, $moduleName)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Superman($container-&gt;make($moduleName));</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">// 向该 超级工厂添加超能力模组的生产脚本</span></div><div class="line">$container-&gt;bind(<span class="string">'xpower'</span>, <span class="function"><span class="keyword">function</span><span class="params">($container)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> XPower;</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">// 同上</span></div><div class="line">$container-&gt;bind(<span class="string">'ultrabomb'</span>, <span class="function"><span class="keyword">function</span><span class="params">($container)</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> <span class="keyword">new</span> UltraBomb;</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="comment">// ****************** 华丽丽的分割线 **********************</span></div><div class="line"><span class="comment">// 开始启动生产</span></div><div class="line">$superman_1 = $container-&gt;make(<span class="string">'superman'</span>, <span class="string">'xpower'</span>);</div><div class="line">$superman_2 = $container-&gt;make(<span class="string">'superman'</span>, <span class="string">'ultrabomb'</span>);</div><div class="line">$superman_3 = $container-&gt;make(<span class="string">'superman'</span>, <span class="string">'xpower'</span>);</div><div class="line"><span class="comment">// ...随意添加</span></div></pre></td></tr></table></figure></p>
</blockquote>
<h1 id="动手写一个简单的容器"><a href="#动手写一个简单的容器" class="headerlink" title="动手写一个简单的容器"></a>动手写一个简单的容器</h1><ul>
<li><p>动手写一个容器 container：</p>
<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"></div><div class="line"><span class="keyword">namespace</span> <span class="title">core</span>\<span class="title">lib</span>;</div><div class="line"></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">container</span> </span>&#123;</div><div class="line">    <span class="keyword">public</span> $binds;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * <span class="doctag">@param</span> string $abstract 接口名</div><div class="line">     * <span class="doctag">@param</span> string $concrete 实例名</div><div class="line">     */</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">bind</span><span class="params">($abstract, $concrete)</span> </span>&#123;</div><div class="line">        <span class="keyword">$this</span>-&gt;binds[$abstract] = $concrete;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * <span class="doctag">@param</span> string $className 接口或实例名</div><div class="line">     * <span class="doctag">@return</span> object 根据接口或对象,返回实例化后的对象</div><div class="line">     * <span class="doctag">@throws</span> \Exception</div><div class="line">     */</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">build</span><span class="params">($className)</span> </span>&#123;</div><div class="line">        dump($className);</div><div class="line">        <span class="comment">// 如果是回调函数,则直接调用</span></div><div class="line">        <span class="keyword">if</span> ($className <span class="keyword">instanceof</span> \Closure) &#123;</div><div class="line">            <span class="keyword">return</span> $className();</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 创建反射类</span></div><div class="line">        $reflector = <span class="keyword">new</span> \ReflectionClass($className);</div><div class="line">        <span class="comment">// 如果是接口,则查找对应的绑定实例</span></div><div class="line">        <span class="keyword">if</span> ($reflector-&gt;isInterface()) &#123;</div><div class="line">            <span class="keyword">if</span> (<span class="keyword">isset</span>(<span class="keyword">$this</span>-&gt;binds[$className])) &#123;</div><div class="line">                <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;build(<span class="keyword">$this</span>-&gt;binds[$className]);</div><div class="line">            &#125; <span class="keyword">else</span> &#123;</div><div class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> \<span class="keyword">Exception</span>($className . <span class="string">'接口没有对应实现'</span>);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 不能实例化，抛异常</span></div><div class="line">        <span class="keyword">if</span> (!$reflector-&gt;isInstantiable()) &#123;</div><div class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> \<span class="keyword">Exception</span>(<span class="string">"Target [$className] is not instantiable."</span>);</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 创建构造器</span></div><div class="line">        $constructor = $reflector-&gt;getConstructor();</div><div class="line">        <span class="comment">// 没有构造函数</span></div><div class="line">        <span class="keyword">if</span> ($constructor === <span class="keyword">null</span>) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">new</span> $className;</div><div class="line">        &#125;</div><div class="line">        <span class="comment">// 获取构造函数参数</span></div><div class="line">        $dependencies = $constructor-&gt;getParameters();</div><div class="line">        <span class="comment">// 获取依赖实例对象</span></div><div class="line">        $instances = <span class="keyword">$this</span>-&gt;getDependencies($dependencies);</div><div class="line">        <span class="comment">// 实例化对象</span></div><div class="line">        <span class="keyword">return</span> $reflector-&gt;newInstanceArgs($instances);</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * <span class="doctag">@param</span> array $parameters 获取依赖</div><div class="line">     * <span class="doctag">@return</span> array</div><div class="line">     * <span class="doctag">@throws</span> \Exception</div><div class="line">     */</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getDependencies</span><span class="params">(array $parameters)</span> </span>&#123;</div><div class="line">        $dependencies = [];</div><div class="line"></div><div class="line">        <span class="keyword">foreach</span> ($parameters <span class="keyword">as</span> $parameter) &#123;</div><div class="line">            $dependency = $parameter-&gt;getClass();</div><div class="line">            <span class="keyword">if</span> ($dependency) &#123;</div><div class="line">                $dependencies[] = <span class="keyword">$this</span>-&gt;build($dependency-&gt;name);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> (<span class="keyword">array</span>)$dependencies;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>然后增加一个服务提供者（注册服务）provider</p>
<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="keyword">namespace</span> <span class="title">core</span>\<span class="title">lib</span>;</div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">provider</span></span>&#123;</div><div class="line"></div><div class="line">    <span class="comment">// 注册服务</span></div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">register</span><span class="params">(container $container)</span></span>&#123;</div><div class="line">        $container-&gt;bind(<span class="string">'app\model\UserInterface'</span>, <span class="string">'app\model\UserMysql'</span>);</div><div class="line">        <span class="comment">// ...</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>入口文件调用provider和container</p>
<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"></div><div class="line"><span class="keyword">namespace</span> <span class="title">core</span>;</div><div class="line"></div><div class="line"><span class="keyword">use</span> <span class="title">core</span>\<span class="title">lib</span>\<span class="title">container</span>;</div><div class="line"><span class="keyword">use</span> <span class="title">core</span>\<span class="title">lib</span>\<span class="title">provider</span>;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">ying</span> </span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> $classMap = [];</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 初始化入口方法</div><div class="line">     * 路由匹配</div><div class="line">     */</div><div class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        \core\lib\log::init();</div><div class="line">        $route = <span class="keyword">new</span> \core\lib\route();</div><div class="line">        $ctrl = $route-&gt;ctrl;</div><div class="line">        $action = $route-&gt;action;</div><div class="line">        $ctrl_file = APP . <span class="string">'/ctrl/'</span> . $ctrl . <span class="string">'Ctrl.php'</span>;</div><div class="line">        $ctrl_class = <span class="string">'\\'</span> . MODULE . <span class="string">'\ctrl\\'</span> . $ctrl . <span class="string">'Ctrl'</span>;</div><div class="line">        </div><div class="line">        <span class="keyword">if</span> (is_file($ctrl_file)) &#123;</div><div class="line">            $container = <span class="keyword">new</span> container();</div><div class="line">            <span class="comment">// 注册服务</span></div><div class="line">            provider::register($container);</div><div class="line">            <span class="comment">// 服务启动</span></div><div class="line">            $ctrl_obj = $container-&gt;build($ctrl_class);</div><div class="line">            $ctrl_obj-&gt;$action();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 自动加载方法</div><div class="line">     */</div><div class="line">    <span class="keyword">static</span> <span class="function"><span class="keyword">function</span> <span class="title">load</span><span class="params">($class)</span> </span>&#123;</div><div class="line">        <span class="keyword">if</span> (<span class="keyword">isset</span>($classMap[$class])) &#123;</div><div class="line">            <span class="keyword">return</span> <span class="keyword">true</span>;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            $class = str_replace(<span class="string">'\\'</span>, <span class="string">'/'</span>, $class);</div><div class="line">            $file = YING . $class . <span class="string">'.php'</span>;</div><div class="line">            <span class="keyword">if</span> (is_file($file)) &#123;</div><div class="line">                <span class="keyword">include</span> $file;</div><div class="line">                <span class="keyword">self</span>::$classMap[$class] = $file;</div><div class="line">            &#125; <span class="keyword">else</span> &#123;</div><div class="line">                <span class="keyword">return</span> <span class="keyword">false</span>;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>创建一对一的接口与实例</p>
<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="class"><span class="keyword">interface</span> <span class="title">UserInterface</span> </span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getAll</span><span class="params">()</span></span>;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">set</span><span class="params">()</span></span>;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">delete</span><span class="params">()</span></span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">UserMysql</span> <span class="keyword">implements</span> <span class="title">UserInterface</span></span>&#123;</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">getAll</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">return</span> <span class="string">'this is UserMysql get all'</span>;</div><div class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement getAll() method.</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">set</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement set() method.</span></div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">delete</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="comment">// <span class="doctag">TODO:</span> Implement delete() method.</span></div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>在控制器中应用</p>
<figure class="highlight php"><table><tr><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line"><span class="keyword">namespace</span> <span class="title">app</span>\<span class="title">ctrl</span>;</div><div class="line"></div><div class="line"><span class="keyword">use</span> <span class="title">app</span>\<span class="title">model</span>\<span class="title">UserInterface</span>;</div><div class="line"></div><div class="line"><span class="class"><span class="keyword">class</span> <span class="title">indexCtrl</span></span>&#123;</div><div class="line">    <span class="keyword">protected</span> $user;</div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">__construct</span><span class="params">(UserInterface $user)</span> </span>&#123;</div><div class="line">        <span class="keyword">$this</span>-&gt;user = $user;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">index</span><span class="params">()</span></span>&#123;</div><div class="line">        <span class="keyword">echo</span> <span class="keyword">$this</span>-&gt;user-&gt;getAll();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
</li>
<li><p>小结</p>
<blockquote>
<p>真正的框架容器虽然是这个原理，但是功能要比这强大的多，比如用到了<code>ArrayAccess</code>类， <code>Closure</code>类；绑定接口的可能不只是简单的类的实例，还有可能是回调函数。</p>
</blockquote>
</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/php/正则/" rel="next" title="">
                <i class="fa fa-chevron-left"></i> 
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/security/公钥与私钥/" rel="prev" title="公钥与私钥">
                公钥与私钥 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="cloud-tie-wrapper" class="cloud-tie-wrapper"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://sfault-avatar.b0.upaiyun.com/416/326/4163260007-58a1621e63a68_huge256"
               alt="chimps" />
          <p class="site-author-name" itemprop="name">chimps</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">59</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">12</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">19</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#依赖注入"><span class="nav-number">1.</span> <span class="nav-text">依赖注入</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-依赖"><span class="nav-number">1.1.</span> <span class="nav-text">1. 依赖</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-依赖注入"><span class="nav-number">1.2.</span> <span class="nav-text">2. 依赖注入</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#工厂模式"><span class="nav-number">2.</span> <span class="nav-text">工厂模式</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#loc容器（依赖注入和控制反转）"><span class="nav-number">3.</span> <span class="nav-text">loc容器（依赖注入和控制反转）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#动手写一个简单的容器"><span class="nav-number">4.</span> <span class="nav-text">动手写一个简单的容器</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">chimps</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  








  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  
    
    <script>
      var cloudTieConfig = {
        url: document.location.href, 
        sourceId: "",
        productKey: "48bb30d8783d4b38ba0c95e0283238ca",
        target: "cloud-tie-wrapper"
      };
    </script>
    <script src="https://img1.ws.126.net/f2e/tie/yun/sdk/loader.js"></script>
  










  





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

</body>
</html>
